package em.ctrl;

import base.ctrl.BaseController;
import base.jfinal.JsonUtil;
import base.jfinal.PermissionInterceptor;
import base.jfinal.anatation.RouteBind;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import em.model.*;
import em.util.CommonTools;
import em.util.MD5Util;

import java.sql.Timestamp;
import java.util.*;

@RouteBind(path = "AccountManage")
public class AccountCtrl extends BaseController {
	@Clear({PermissionInterceptor.class})
	public void logout(){
		getRequest().getSession().invalidate();
		renderJson("{\"err\":0}");
	}
	@Clear({PermissionInterceptor.class})
    public void getIsLogin(){
        if(this.getRequest().getSession(false)!=null && this.getRequest().getSession(false).getAttribute("SessionVO")!=null){
            renderJson("{\"err\":0}");
        }else{
            renderJson("{\"err\":1}");
        }
    }
	public void getNavData() {
		List<Record> Menus=getData("org.getNavData",getParas());

		Record Account = Db
				.findFirst(
						"SELECT AccountId,a.`Name` 'LoginName',o.`Name` 'OrgName' FROM em_account a,em_org o WHERE a.OrgId=o.OrgId AND a.AccountId=?",
						getParaToInt("GlobalAccId"));
		JSONObject acc = JSON.parseObject(Account.toJson());
		acc.put("MenuList", Menus);
		JSONArray jsonArray=CommonTools.getInstance().findSub(JSONArray.parseArray(JsonUtil.toJSONString(Menus)),"","PId","MenuId");
		acc.put("NewMenuList",jsonArray);
		renderJson(acc);
	}

	public void getOrgListByOrgId() {
		List OrgList=getData("org.getOrgListByPid", getParas());
		renderJson(OrgList);
	}

	public void getAccountById() {
		Record accs=Db.findFirst(CommonTools.getInstance().getSql("emp.getAccountById", getParas()));
		renderJson(accs);
	}

	@Before(Tx.class)
	public void createAccount() {
		int err = isExistAcc(this.getPara("Name"), this.getPara("Email"));
		if (err > 0) {
			renderJson("{\"err\":" + err + "}");
		} else {
			String password = this.getPara("PassWord");
			HashMap<String, Object> dataMap = (HashMap<String, Object>) this
					.getParas();
			dataMap.put("Password", MD5Util.getInstance().getMD5(password));
			Org org = Org.dao.findById(this.getPara("OrgId"));
			Account acc = new Account().setValues(dataMap).remove("AccountId")
					.set("CreateBy", getParaToInt("GlobalAccId"))
					.set("CreateDate", new Date());
			//if (org.getStr("Type").equals("2")) {
			//	acc.set("Company", org.getInt("PID"));
			//} else {
			acc.set("Company", org.getInt("OrgId"));
			//}
			acc.save();
			renderJson("{\"err\":" + err + "}");
		}
	}

	@Before(Tx.class)
	public void modifyAccount() {
		Account acc = Account.dao
				.findFirst("SELECT * FROM em_account WHERE `Name`=?",
						this.getPara("Name"));
		if (!acc.getInt("AccountId").equals(getParaToInt("AccountId"))) {
			renderJson("{\"err\":1}");
			return;
		}
		acc = Account.dao.findFirst("SELECT * FROM em_account WHERE Email=?",
				this.getPara("Email"));
		if (!acc.getInt("AccountId").equals(getParaToInt("AccountId"))) {
			renderJson("{\"err\":2}");
			return;
		}
		HashMap<String, Object> dataMap = (HashMap<String, Object>) this
				.getParas();
		if (this.getPara("PassWord") == null) {
			dataMap.remove("PassWord");
		} else {
			String Pw = this.getPara("PassWord");
			dataMap.put("PassWord", MD5Util.getInstance().getMD5(Pw));
		}
		acc.setValues(dataMap).update();

		renderJson("{\"err\":0}");
	}

	public int isExistAcc(String Name, String Email) {
		List Acc4Names = Db.find("SELECT * FROM em_account WHERE `Name`=?",
				Name);
		if (Acc4Names.size() > 0) {
			return 1;
		}
		List Acc4Emails = Db.find("SELECT * FROM em_account WHERE Email=?",
				Email);
		if (Acc4Emails.size() > 0) {
			return 2;
		}
		return 0;
	}

	/**
	 * 用户登录
	 */
	@Clear({PermissionInterceptor.class})
	public void login(){
		String email =getPara("email");
		String password=MD5Util.getInstance().getMD5(getPara("password"));
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("email", email);
		//根据帐号取得数据
		Record record=Db.findFirst(CommonTools.getInstance().getSql("emp.getAccountByemail", map));
		if(record==null){
			this.renderJson("{\"err\":1}");
		}else if(!record.getStr("PassWord").equals(password)){
			this.renderJson("{\"err\":1}");// 账号或密码错误
		}else if(record.getStr("Status").equals("1")){
			this.renderJson("{\"err\":2}");// 账号被停用
		}else{
			map.clear();
			map.put("GlobalAccId", record.getInt("AccountId"));
			List<Record> lstPrivs=Db.find(CommonTools.getInstance().getSql("emp.getPrivilegeListById",map));
			List<String> lst=new ArrayList<String>();
			for (Record record1:lstPrivs){lst.add(record1.getStr("privilegeId"));}

			SessionVO ses=new SessionVO();
			ses.setAccountId(record.getInt("AccountId"));
			ses.setOrgId(record.getInt("OrgId"));
			ses.setPrivilegeList(JSONArray.toJSONString(lst));
			ses.setSoureIp(this.getRequest().getRemoteAddr());
			ses.setCompany(record.getInt("Company"));
			ses.setOrgName(record.getStr("orgName"));
			ses.setAccType(record.getInt("Type"));
			ses.setOrgType(record.getInt("orgType"));
			this.getRequest().getSession().setAttribute("SessionVO", ses);//session保存
			Logger logger=new Logger();
			logger.set("AccountId", record.getInt("AccountId")).set("Model", "账号管理").set("Operation", "登录").set("Desc", "").set("SoureIp", this.getRequest().getRemoteAddr()).save();
			this.renderJson("{\"err\":0,\"AccType\":"+record.getInt("Type")+"}");//账号密码验证通过,状态正常
		}
	}

	/**
	 * 修改账号
	 * @return err:1登录邮箱重复;err:2用户名重复;err:0成功
	 */
	public void modifiyAcc() {
		Integer accId= Integer.getInteger(this.getRequest().getAttribute("AccountId").toString());
		Map<String, Object> map=getParas();
		map.put("UpdateBy", accId);
		map.put("UpdateDate", new Timestamp(new Date().getTime()));
		Record reEmail=Db.findFirst(CommonTools.getInstance().getSql("emp.isExistEmail", map));
		Record reName=Db.findFirst(CommonTools.getInstance().getSql("emp.isExistName", map));
		if(reEmail!=null && StrKit.notBlank(reEmail.getStr("email")) && !reEmail.getStr("email").equals(map.get("originalEmail").toString())){
			renderJson("{\"err\":1}");//邮箱重复
		}else if(reName!=null && StrKit.notBlank(reName.getStr("name")) && !reName.getStr("name").equals(map.get("originalName").toString())){
			renderJson("{\"err\":2}");//用户名重复
		}else{
			Account.dao.findById(map.get("accountId").toString()).setValues(map).update();
			new Logger().set("AccountId",getParaToInt("GlobalAccId")).set("Model", "账号管理").set("Operation", "修改账号").set("Desc", "账号:"+ map.get("name")+","+map.get("email")).set("SoureIp", this.getRequest().getRemoteAddr()).save();
			renderJson("{\"err\":0}");
		}
	}
	
	/**
	 * 创建账号
	 * @return err:1登录邮箱重复;err:2用户名重复;err:0成功
	 */
	public void createAcc() {
		Integer createBy=getParaToInt("GlobalAccId");
		Map<String, Object> map=getParas();
		map.put("PassWord", MD5Util.getInstance().getMD5(map.get("PassWord").toString()));
		
		Org org=Org.dao.findById(map.get("OrgId"));
		if("2".equals(org.getStr("Type"))){
			map.put("Company", org.get("Pid"));
		}else{
			map.put("Company", map.get("OrgId"));
		}
		
		Record reEmail=Db.findFirst(CommonTools.getInstance().getSql("emp.isExistEmail", map));
		Record reName=Db.findFirst(CommonTools.getInstance().getSql("emp.isExistName", map));
		if(reEmail!=null && StrKit.notBlank(reEmail.getStr("email"))){
			renderJson("{\"err\":1}");//邮箱重复
		}else if(reName!=null && StrKit.notBlank(reName.getStr("name"))){
			renderJson("{\"err\":2}");//用户名重复
		}else{
			map.put("CreateDate", new Date());
			map.put("CreateBy", createBy);
			new Account().setValues(map).save();
			
			Account.dao.findById(map.get("accountId").toString()).setValues(map).update();
			new Logger().set("AccountId",getParaToInt("GlobalAccId")).set("Model", "账号管理").set("Operation", "创建账号").set("Desc", "账号:"+ map.get("name")+","+map.get("email")).set("SoureIp", this.getRequest().getRemoteAddr()).save();
			renderJson("{\"err\":0}");
		}		
	}
	
	/**
	 * 启用账号
	 * @return err:1所属组织已被禁用;err:0成功;
	 */
	public void enabledAcc() {
		Map<String, Object> map=getParas();
		Account account=Account.dao.findById(map.get("accId"));
		Org org=Org.dao.findById(account.getInt("OrgId"));
		if(org!=null && "0".equals(org.getStr("status"))){
			account.set("status", "0");
			Db.update(CommonTools.getInstance().getSql("emp.enabledWxAcc", map));
			account.update();
			new Logger().set("AccountId",getParaToInt("GlobalAccId")).set("Model", "账号管理").set("Operation", "启用账号").set("Desc", "账号名称:"+ account.getStr("name")+",登录邮箱:"+account.getStr("email")).set("SoureIp", this.getRequest().getRemoteAddr()).save();
			renderJson("{\"err\":0}");
		}else{
			renderJson("{\"err\":1}");//所属组织被禁用
		}
	}
	
	/**
	 * 禁用账号
	 * @return err:0 成功
	 */
	public void disabledAcc() {
		Account account=Account.dao.findById(getPara("accId"));
		account.set("status", "1").update();
		Db.update("UPDATE em_account_wechat set `status`='1' where accountid=?",getPara("accId"));
		new Logger().set("AccountId",getParaToInt("GlobalAccId")).set("Model", "账号管理").set("Operation", "禁用账号").set("Desc", "账号名称:"+ account.getStr("name")+",登录邮箱:"+account.getStr("email")).set("SoureIp", this.getRequest().getRemoteAddr()).save();
		renderJson("{\"err\":0}");
	}
	
	/**
	 * 修改密码
	 * @return err:0 成功 1 登录密码错误
	 */
	public void modifiyPassword() {
		String oldPassword=MD5Util.getInstance().getMD5(getPara("oldPassWord"));
		Account account=Account.dao.findById(getParaToInt("GlobalAccId"));
		if(account!=null && account.getStr("PassWord").equals(oldPassword)){
			account.set("PassWord", MD5Util.getInstance().getMD5(getPara("newPassWord"))).update();
			renderJson("{\"err\":0}");
		}else{
			renderJson("{\"err\":1}");//登录密码不正确
		}
	}

	public void deleteWxAcc() {
		Db.update(CommonTools.getInstance().getSql("emp.deleteWxAcc",getParas()));

		renderJson ("{\"err\":0}");
	}
}